package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.service.WxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;
    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;

    @Override
    public Map<String, String> wxLogin(String code) {
        try {
            HashMap<String, String> map = new HashMap<>();
            //获取openId
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            String openId = sessionInfo.getOpenid();
            //通过openId查询用户
            UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openId));
            //用户为空，注册用户
            if (BeanUtil.isEmpty(userInfo)) {
                UserInfo userInfo1 = new UserInfo();
                userInfo1.setWxOpenId(openId);
                userInfo1.setNickname("听书" + IdUtil.simpleUUID());
                userInfo1.setAvatarUrl("http://192.168.200.6:9000/tingshu/User/User.jpg");
                userInfoMapper.insert(userInfo1);

                //3.2 隐式初始化账户记录
                //3.2.1 构建初始化账户所需参数对象
                Map<String, Object> mapData = new HashMap<>();
                mapData.put("userId", userInfo1.getId());
                mapData.put("title", "首次登录赠送体验金");
                mapData.put("amount", new BigDecimal("10"));
                mapData.put("orderNo", "zs" + IdUtil.getSnowflakeNextId());
                //3.2.2 调用发送消息工具类方法发送消息(生产者)
                rabbitService.sendMessage(MqConst.EXCHANGE_USER, MqConst.ROUTING_USER_REGISTER, mapData);

            }
//	用户不为空，赋值token
            String token = IdUtil.randomUUID();
            String userKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
            UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class);
            redisTemplate.opsForValue().set(userKey, userInfoVo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
            map.put("token", token);
            return map;
        } catch (Exception e) {
            log.error("[用户登录]：发生异常");
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
    }

    /**
     * 修改用户信息
     *
     * @param userInfoVo
     */
    @Override
    public void updateUser(UserInfoVo userInfoVo) {
        Long userId = AuthContextHolder.getUserId();
        UserInfo userInfo = BeanUtil.copyProperties(userInfoVo, UserInfo.class);
        userInfo.setId(userId);
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 判断用户是否购买过该声音
     *
     * @param userId
     * @param albumId
     * @param trackInfoList
     * @return
     */
    @Override
    public Map<Long, Integer> userIsPaidTrack(Long userId, Long albumId, List<Long> needCheckBuyStateTrackIds) {
        //1 创建一个map集合，用于封装数据
        HashMap<Long, Integer> map = new HashMap<>();
        //2 查询用户是否购买过该专辑
        LambdaQueryWrapper<UserPaidAlbum> userPaidAlbumLambdaQueryWrapper = new LambdaQueryWrapper<UserPaidAlbum>()
                .eq(UserPaidAlbum::getUserId, userId)
                .eq(UserPaidAlbum::getAlbumId, albumId);
        Long flag = userPaidAlbumMapper.selectCount(userPaidAlbumLambdaQueryWrapper);
        //2.1 购买过，则全部的声音的值都为1
        if (flag > 0) {
            for (Long needCheckBuyStateTrackId : needCheckBuyStateTrackIds) {
                map.put(needCheckBuyStateTrackId, 1);
            }
            return map;
        }
        //2.2 未购买，则判断用户是否购买过该声音
        //3 查询用户是否购买过该声音
        LambdaQueryWrapper<UserPaidTrack> userPaidTrackLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPaidTrackLambdaQueryWrapper.eq(UserPaidTrack::getUserId, userId);
        userPaidTrackLambdaQueryWrapper.eq(UserPaidTrack::getAlbumId, albumId);
        userPaidTrackLambdaQueryWrapper.in(UserPaidTrack::getTrackId, needCheckBuyStateTrackIds);
        List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(userPaidTrackLambdaQueryWrapper);
        List<Long> userPaitTrackIdList = userPaidTrackList.stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(userPaitTrackIdList)) {
            //3.1 购买过，则包含的声音的值都为1
            for (Long needCheckBuyStateTrackId : needCheckBuyStateTrackIds) {
                if (userPaitTrackIdList.contains(needCheckBuyStateTrackId)) {
                    map.put(needCheckBuyStateTrackId, 1);
                } else {
                    map.put(needCheckBuyStateTrackId, 0);
                }
            }
        } else {
            //没有买任何的声音
            for (Long needCheckBuyStateTrackId : needCheckBuyStateTrackIds) {
                map.put(needCheckBuyStateTrackId, 0);
            }
        }
        return map;
    }
}
